package logic

import (
	"context"
	tools "go-zero-project/common/utils"
	"go-zero-project/services/project/rpc/internal/mapper"
	"go-zero-project/services/project/rpc/internal/mapper/entity/bo"

	"go-zero-project/services/project/rpc/internal/svc"
	"go-zero-project/services/project/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListPageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListPageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListPageLogic {
	return &ListPageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListPageLogic) ListPage(in *pb.SearchProjectReq) (*pb.SearchProjectResp, error) {
	// convert bo
	projectMapper := mapper.NewProjectMapper(l.svcCtx.ElasticSearchClient)
	projectBO := l.convertBo(in)
	// query
	resp, searchErr := projectMapper.SearchPageList(projectBO)
	if searchErr != nil {
		return nil, searchErr
	}
	// return obj ...
	result := new(pb.SearchProjectResp)
	result.TotalPage = int32(resp.TotalPage)
	result.PageNum = int32(resp.PageNum)
	result.PageSize = int32(resp.PageSize)
	records := resp.Records
	var retList []*pb.ProjectInfo
	if len(records) > 0 {
		for _, v := range records {
			info := new(pb.ProjectInfo)
			tools.JsonToBean(tools.BeanToJson(v), info)
			retList = append(retList, info)
		}
	}
	result.Records = retList
	return result, nil
}

func (l *ListPageLogic) convertBo(in *pb.SearchProjectReq) bo.ProjectBO {
	projectBO := bo.ProjectBO{}
	projectBO.PageSize = in.PageSize
	projectBO.PageNum = in.PageNum
	projectBO.IndustryParentId = in.IndustryParentId
	projectBO.IndustryId = in.IndustryId
	projectBO.ProvinceId = in.EnterpriseProvinceId
	projectBO.CityId = in.EnterpriseCityId
	projectBO.DistrictId = in.EnterpriseDistrictId
	projectBO.ResourceRaise = in.ResourceRaise
	projectBO.RoofAreaRange = in.RoofAreaRange
	projectBO.ProjectRoofType = in.ProjectRoofType
	projectBO.CompanyType = in.CompanyType
	projectBO.PersonnelSizeType = in.PersonnelSizeType
	projectBO.InstalledPV = in.InstalledPVType
	projectBO.Keyword = in.Keyword
	orders := in.Orders
	var orderArr []bo.SearchOrder
	if len(orders) > 0 {
		for _, v := range orders {
			orderArr = append(orderArr, bo.SearchOrder{FieldName: v.FieldName, Order: v.Order})
		}
	}
	projectBO.Orders = orderArr
	return projectBO
}
